define(['app','pagination','datetime','js/directive/listTree','js/filter/tree2Arr'], function( appCRM ) {
'use strict';
/*后台员工管理*/
appCRM.controller('User', function ($scope, $http, dataFactoryCRM , $q, $timeout) {
    $scope.search_param = {user:'',status:-2,role:-1,sector:-1,};
	$scope.editData = {user_id:0};
    $scope.userRoleSector = {user_id:0};
    $scope.pagerdata = { pageAll:1, pageNow:1, pageSize:$scope.psize, k: 3922 };
	$("#check_all").click(function(){
		$("input[class='check_list']").prop('checked', $(this).prop("checked"));
	});
	/*系统错误调用*/
    $scope.msgAttention = function() {
        $('.ui.systemerror').modal({
            closable: true,
            onDeny: function() {
                return true;
            },
            onApprove: function() {
                $('.ui.dimmer.modals.page.transition.visible.active.dimmers').removeClass('dimmers');
            }
        }).modal('show');

        setTimeout(function() {
            var system = $('.ui.dimmer.modals.page.transition.visible.active');
            if (system) {
                $('.ui.dimmer.modals.page.transition.visible.active').addClass('dimmers');
            }
        }, 1000);
    };

	//分页
	$scope.pagerdata = {pageAll: 1,pageNow: 1, pageSize:$scope.psize,k: 3};
	$scope.user;
	//获取分页数据
	$scope.getPageData = function(){
		var sUrl = "user/index";
        var _param =  $scope.search_param;
        _param['psize'] = $scope.pagerdata.pageSize;
        _param['p'] = $scope.pagerdata.pageNow;
		sUrl +=	"?"+$.param( _param ) ;
		$scope.$emit("BUSY");
  		dataFactoryCRM.getDataByAPI( sUrl ).then( function( _d ){
            $scope.users = _d.data;
            $scope.pagerdata.pageSize = _d.psize;
			$scope.pagerdata.pageAll = _d.pall;
			$scope.pagerdata.pageNow = _d.p;
			$scope.$emit("NOTBUSY");
  		});
	}
    window.loadClientCacheToScope($scope, function(){
            $scope.getPageData();
        });
	
    //加载部门
	$scope.busy = dataFactoryCRM.getDataByAPI('user/getPageParam')
    	.then( function( data ) {
    		$scope.busy = false;
            if( data ) {
                $scope.sectors = data.sector;
				$scope.roles = data.role;
            }
    	});

    //用户搜索
	$scope.search = function(){
		$scope.getPageData();
	}

	//重置密码框
	$scope.resetPass = function( user_id ){
        function _resetPass(){
            $scope.$emit("BUSY");
            dataFactoryCRM.postDataByAPI( "user/resetPass", $scope.resetData )
                .then( function( _d ){
                    $scope.$emit("NOTBUSY");
                    if ( _d&&_d.rcode) {
                        $scope.api_success("用户密码更新成功");
                        return true;
                    }else{
                        $scope.api_error("用户密码更新失败");
                        return false;
                    }
                });
        }
        $('#pwd_reset').form('clear');
        dataFactoryCRM.getDataByAPI('user/saveEdit?user_id='+user_id )
                .then(function(d){
                if (d&&d.rcode) {
                        $timeout(function(){
                            $scope.resetData = d.data;
                        });
                     $('.ui.reset_confirm.modal').modal({
                        onApprove:function(){
                            $('.ui.reset_pass.modal').modal({
                                onApprove:function(){
                                    if ($('#pwd_reset').form()){
                                        _resetPass();
                                    }
                                    else
                                        return false;
                                }
                            }).modal('show');
                            return false;
                        }
                    }) .modal('show');
                }
                else{
                    $scope.api_error( d.msg );
                }
            },
            function(){
                $scope.api_error('接口请求失败');
            }
        );
	}


	//重置密码
	$scope.resetPass2 = function( uid ){
		var _uid = $('#chunid').html();
		var _lname = $('#chnickname').html();
		var _pwd = $('#czpwd').val();
 		if( $('#pwd_reset').form('is valid') ){
 			$scope.$emit("BUSY");
 			dataFactoryCRM.postDataByAPI( "user/resetPass?uid="+_uid+"&pwd="+_pwd )
 				.then( function( _d ){
					$scope.userRcode = _d.rcode;
              		$scope.userMsg = _d.msg;
              		$scope.msgAttention();
					if (_d['rcode']=="1") {
						$scope.getPageData();//重新加载列表
						$scope.$emit("NOTBUSY");
						return true;
					}else{
						$scope.$emit("NOTBUSY");
						return false;
					}
  				});
 		}
        else
            return false;
	}

	$scope.randomNumTimes = function(n){
   		var t = '';
    	for(var i=0;i<n;i++){
        	t += Math.floor(Math.random()*10);
    	}
    	return t;
	}

    $scope.api_error = function ( msg ) {
        $('.modal.modal2').remove();
        $('<div class="ui small modal modal2" style="text-align: center;"><div class="header">提示</div><div class="content"><i class="huge red warning outline icon"></i>' +
            '<p style="padding-top: 15px;">'+msg+'</p>' +'</div></div>'
        ).modal('show');
    };

    $scope.api_success = function( msg ){
        $('.modal.modal1').remove();
        $('<div class="ui small modal modal1" style="text-align: center;"><div class="header">提示</div><div class="content"><i class="huge green check circle outline icon"></i>' +
                '<p style="padding-top: 15px;">'+msg+'</p>' +'</div></div>'
            ).modal('show');
    };

	//修改部门岗位
	$scope.chageRoleSector = function(uid) {
        function showEdit(){
            $('.ui.js.modal').modal({
                onApprove:function(){
                    $scope.$emit("BUSY");
                    $timeout(function(){ $('.ui.js.modal .ui.dropdown').dropdown('refresh'); });
                    dataFactoryCRM.postDataByAPI( 'user/changeRoleSector', $scope.userRoleSector )
                        .then( function( _d ){
                            $scope.$emit("NOTBUSY");
                            if ( _d.rcode){
                                $scope.api_success('部门岗位数据更新成功');
                                $scope.getPageData();
                            }
                            else{
                                $scope.api_error('数据更新失败');
                            }
                        });
                }
            }).modal('show');
        }
        dataFactoryCRM.getDataByAPI('user/saveEdit?user_id=' + uid ).then( function(d) {
            if ( d&&d.rcode==1) {
                $timeout(function(){
                    $scope.userRoleSector = d.data;
                    $('.edit_state').dropdown('set selected', $scope.userRoleSector.state);
                    $('.rs_role').dropdown('set selected', $scope.userRoleSector.role_id);
                    $('.rs_sector').dropdown('set selected', $scope.userRoleSector.sector_id);
                });

                showEdit();
            }
            else {
                $scope.api_error(d.msg);
            }
        },
        function (err){
            $scope.$emit("NOTBUSY");
            $scope.api_error('接口请求失败');
            }
        );

	}

	//添加新用户
	$scope.addUser = function( _d ){
		function _addUser( user ){
			$scope.$emit("BUSY");
			$scope.busy = dataFactoryCRM.postDataByAPI('user/addUser', user )
			.then(function(d){
				$scope.userRcode = d.rcode;
              	$scope.userMsg = d.msg;
				if (d.rcode) {
                    $scope.api_success("用户添加成功");
					$scope.getPageData();//重新加载列表
					return true;
				}else{
					$scope.api_error( d.msg );
                    return false;
				}
			});
		}
		$scope.addData = {login_name:'',nickname:'',sector_id:0,role_id:0,phone:'',qq:'',weixin:'',pwd:'',
							email:'',teacher_name:'',cert_num:'',pwd:'hzhfzx',teacher_name:'',cert_num:''};

        $timeout(function(){
            $('#addfrm').form('clear');
            $('.add_state').dropdown('set selected', 2);
            $scope.addData.login_name = '系统将自动生成';
            $scope.addData.pwd = 'hzhfzx';
       });
		$('.ui.add').modal({
            onApprove: function() {
            	if( $('#addfrm').form('is valid') ){
					return _addUser( $scope.addData);
				}
                else
                    return false;
            }}).modal('show');
	}

	//编辑用户信息
	$scope.editUser = function( user_id) {
		function _updateUser( user ) {
			$scope.$emit("BUSY");
			dataFactoryCRM.postDataByAPI('user/saveEdit', user )
				.then(function(d){
                    $scope.$emit("NOTBUSY");
					$scope.userMsg = d.msg;
					if (d.rcode) {
                        $scope.api_success("用户资料更新成功");
						$scope.getPageData();//重新加载列表
						return true;
					}else{
						$scope.api_error( d.msg );
						return false;
					}
				});
		}

        $timeout(function(){
            if($scope.editUser.user_id && $scope.editUser.user_id!==user_id)
                $('#editfrm').form('clear');
        });
        dataFactoryCRM.getDataByAPI('user/saveEdit?user_id='+user_id )
                .then(function(d){
                if (d&&d.rcode) {
                    $timeout(function(){
                        $timeout(function(){
                            $('.edit_state').dropdown('set selected', $scope.editData.state); });
                            $scope.editData = d.data;
                        });
                     $('.ui.edit.modal').modal({
                        onApprove:function(){
                            if( $('#editfrm').form('is valid') ){
                                _updateUser( $scope.editData );
                            }else  return false;
                        }
                    }) .modal('show');
                }
                else{
                    $scope.api_error( d.msg );
                }
            },
            function(){
                $scope.api_error('接口请求失败');
            }
        );
	}

	//批量删除
	$scope.delAll = function(){
		$('#msg-model .header').html("删除用户");
		$('#msg-model .content p').html("确定要删除用户吗？");
		$('.ui.small.msg').modal({
            onApprove: function() {
				var strdelid = $("input:checkbox[name='chbids']:checked").map(function(index,elem) {
					return $(elem).val();
				}).get().join(',');
				if (strdelid.length < 1) { //没有选择删除项
					return;
				}
				$scope.$emit("BUSY");
		  		dataFactoryCRM.getDataByAPI( "user/userDelAll?ustr="+strdelid ).then( function( _d ){
		  			$scope.userRcode = _d.rcode;
              		$scope.userMsg = _d.msg;
					if (_d['rcode']=="1") {
						if( $scope.user ){
		                  	var i = 0;
		                  	for(;i<$scope.user.length; i++){
		                    	if( $scope.user[i].user_id == _vuser.user_id){
		                     	 	$scope.user.splice(i,1);//在前端删除；
		                      		break;
		                    	}
		                  	}
		                }
		                $scope.$emit("NOTBUSY");
		                $scope.getPageData();//重新加载列表
                		return true;
					}else{
						$scope.$emit("NOTBUSY");
						$scope.msgAttention();
						$scope.getPageData();//重新加载列表
					}
		  		});
            }
        }).modal('show');
	}

    $scope.$watch('search_param.status', function(){
			$scope.pagerdata.pageNow = 1;
            $scope.search();
        });
    }).directive('userStatus', function() {
            return {
                restrict: 'A',
                template: "{{status}}",
                link: function(scope, element, attrs) {
                    if (attrs.status) {
                        //员工状态: 离职员工、禁止登录、试用员工、正式员工
                        var code = parseInt( scope.$eval(attrs.status) );
                        code +=1;
                        code = 'A' + code;
                        var Names = {'A0':'离职员工','A1':'禁止登录','A2':'试用员工','A3':'正式员工'};
                        scope.status = Names[code];
                    }
                }
            };
        });
});
